package com.weixun.cms.controller;

import com.jfinal.json.JFinalJson;
import com.jfinal.kit.JsonKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.weixun.cms.service.MsgService;
import com.weixun.comm.controller.BaseController;
import com.weixun.model.CmsLink;
import com.weixun.model.Msg;
import com.weixun.utils.ajax.AjaxMsg;

import java.util.List;

public class MsgController extends BaseController {
    MsgService msgService = new MsgService();
    /**
     * 基于layui的分页
     */
    public void pages(){
        int pageNumber = getParaToInt("page");
        int pageSize = getParaToInt("limit");
        String msg_content = getPara("msg_content");
        Page<Record> list = msgService.paginate(pageNumber,pageSize,msg_content);//获得用户信息
        renderPageForLayUI(list);
    }


    /**
     * 查询数据列表
     */
    public void list()
    {
        String msg_pk = getPara("msg_pk");
        List<Record> records = msgService.findList(msg_pk);
        renderJson(JFinalJson.getJson().toJson(records));
    }


    /**
     * 删除数据
     */
    public void delete()
    {
        AjaxMsg ajaxMsg = new AjaxMsg();
        String msg_pk = this.getPara("msg_pk");
        int res =msgService.deleteById(msg_pk);
        if (res >0) {
            ajaxMsg.setState("success");
            ajaxMsg.setMsg("删除成功");
        }
        else
        {
            ajaxMsg.setState("fail");
            ajaxMsg.setMsg("删除失败");
        }

        renderJson(ajaxMsg);
    }


    /**
     * 保存方法
     */
    public void save()
    {
        getResponse().addHeader("Access-Control-Allow-Origin", "*");
        AjaxMsg ajaxMsg = new AjaxMsg();
        boolean res = false;

        try {

            Msg msg = getModel(Msg.class,"");
            //保存方法
            res = msg.save();
            if(res)
            {
                ajaxMsg.setState("success");
                ajaxMsg.setMsg("保存成功");
            }
            else
            {
                ajaxMsg.setState("fail");
                ajaxMsg.setMsg("保存失败");
            }
        }catch (Exception e)
        {
            e.getMessage();
            ajaxMsg.setState("fail");
            ajaxMsg.setMsg("保存失败");
        }
//        String callback = getRequest().getParameter("callback");
//        String jsonp = callback+"("+ JsonKit.toJson(ajaxMsg)+")";//返回的json 格式要加callback()
        renderJson(ajaxMsg);
    }

}
